using System;
using System.Collections.Generic;
using System.Windows.Forms;
using CppWrapper.GUI;
using CppWrapper.Interfaces;

namespace WrapperGenerator
{
  public partial class GACBrowser : Form
  {
    private readonly IList<ITypeInfo> typeInfo=new List<ITypeInfo>();
    private IAssemblyInfo assembly;

    public GACBrowser()
    {
      InitializeComponent();
      DialogResult = System.Windows.Forms.DialogResult.Cancel;
    }

    public IEnumerable<ITypeInfo> TypeInfo
    {
      get { return typeInfo; }
    }

    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);
      FillAssemblyListAsync();
    }


    private IAsyncResult FillAssemblyListAsync()
    {
      return new FillAssemblyListHandler(FillAssemblyList).BeginInvoke(null, null);
    }

    private delegate void FillAssemblyListHandler();

    private void FillAssemblyList()
    {
      IAssemblyEnum assemblyEnum =  AssemblyCache.CreateGACEnum();
      IAssemblyName name;
      while (assemblyEnum.GetNextAssembly(new IntPtr(), out name, 0)==0)
      {
        string assemblyName = AssemblyCache.GetName(name);
        IAssemblyInfo info = new AssemblyInfo();
        info.Name = assemblyName;
        info.PublicKeyToken = AssemblyCache.GetPublicKeyToken(name);
        info.Version = AssemblyCache.GetVersion(name);
        info.Full = AssemblyCache.GetDisplayName(name, ASM_DISPLAY_FLAGS.PUBLIC_KEY_TOKEN | ASM_DISPLAY_FLAGS.CULTURE|ASM_DISPLAY_FLAGS.VERSION);
        Invoke(new MethodInvoker(delegate
                                   {
                                     gacList.Items.Add(info);
                                   }
                 ));
        
      }
    }

    private void button1_Click(object sender, EventArgs e)
    {
      Close();
    }

    private void OnApplyClick(object sender, EventArgs e)
    {
      SetCurrentSelectionAsResult();
      ExitWithOK();
    }

    private void ExitWithOK()
    {
      DialogResult = System.Windows.Forms.DialogResult.OK;
      Close();
    }

    private void OnGacListDoubleClick(object sender, EventArgs e)
    {
      SetCurrentSelectionAsResult();
      ExitWithOK();
    }

    public IAssemblyInfo Assembly
    {
      get { return assembly; }
      private set { assembly = value; }
    }

    private void SetCurrentSelectionAsResult()
    {
      Assembly = (IAssemblyInfo) gacList.SelectedItem;
    }
  }
}